<template>
  <div class="dashboard-container">
    <div class="dashboard-content">
      <!-- 左侧信息面板 -->
      <div class="left-panel">
        <cardBox title="大坝实时安全评价" icon="&#xe638;" isMore @more="dbDialogVisible = true">
          <template #right>
            <div class="date-box">
              <el-input prefix-icon="el-icon-date" style="width:160px" v-model="timeSign" readonly 
                       @focus="showDateBox = true" placeholder="请选择要查询月份" size="small"/>
              <div class="shape" v-show="showDateBox" @click="showDateBox = false"></div>
              <calendar v-show="showDateBox" class="date-con" :eventData="eventData" 
                       @month-select="handleSelectMonth" />
            </div>
          </template>
          <div class="card-body">
            <el-table
              v-loading="loading.table1"
              :data="tableData1" 
              height="calc(100vh - 600px)" 
              border 
              row-key="index_id"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}" 
              stripe 
              empty-text="暂无数据"
            >
              <el-table-column prop="indexName" label="部位" show-overflow-tooltip>
              </el-table-column>
              <el-table-column label="等级" align="center" width="90">
                <template slot-scope="scope">
                  <el-tag :type="getGradeTagType(scope.row.grade)" size="small">
                    {{ getGradeDisplayText(scope.row.grade) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="异常指标统计" align="center">
                <el-table-column prop="nomal" label="正常" width="50" align="center"></el-table-column>
                <el-table-column prop="Ⅲ" label="Ⅲ级" width="50" align="center"></el-table-column>
                <el-table-column prop="Ⅱ" label="Ⅱ级" width="50" align="center"></el-table-column>
                <el-table-column prop="Ⅰ" label="Ⅰ级" width="50" align="center"></el-table-column>
              </el-table-column>
            </el-table>
          </div>
        </cardBox>

        <cardBox title="巡视检查" icon="&#xe7b0;" isMore @more="xsDialogVisible = true">
          <div class="card-body inspection">
            <noData showData v-if="tableData4.length === 0" style="height:200px"/>
            <div v-else class="inspection-list">
              <el-scrollbar>
                <div class="inspection-container">
                  <div v-for="(item, index) in tableData4" :key="index" class="inspection-item">
                    <div class="item-header">
                      <div class="header-main">
                          <el-tooltip effect="dark" content="巡查部位" placement="top-start">
                            <span class="location">
                              <i class="el-icon-location-outline"></i>
                              {{ item.treeName || '--' }}
                            </span>
                          </el-tooltip>
                        
                       
                      </div>
                      <div class="header-status">
                        <el-tooltip class="item" effect="dark" content="评判结果" placement="top-start">
                          <el-tag 
                          :type="getJudgementTagType(item.judgement)" 
                          size="small"
                          class="judgement-tag"
                          v-if="item.judgement"
                        >
                          {{ getJudgementDisplayText(item.judgement) }}
                        </el-tag>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="未审核" placement="top-start">
                           <i class="iconfont greyText ico" v-if="item.status == 0">&#xe645;</i>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="审核通过" placement="top-start">
                            <i class="iconfont greenText ico" v-if="item.status == 1">&#xe630;</i>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="审核不通过" placement="top-start">
                            <i class="iconfont redText ico" style="font-size:18px" v-if="item.status == 2">&#xe654;</i>
                        </el-tooltip>
                      </div>
                    </div>

                    <!-- 内容区域 -->
                    <div class="item-content">
                      <div class="content-row">
                        <span class="label">巡视要求：</span>
                        <span class="value">{{ item.request || '--' }}</span>
                      </div>
                      <div class="content-row">
                        <span class="label">巡查内容：</span>
                        <span class="value content-text">{{ item.cont || '--' }}</span>
                      </div>
                      <div class="content-row">
                        <span class="label">巡查情况：</span>
                        <span class="value content-text">{{ item.remark || '--' }}</span>
                      </div>
                    </div>
                    <div class="item-footer">
                        <el-tooltip class="item" effect="dark" content="巡查人员" placement="top-start">
                          <span class="inspector">
                            <i class="el-icon-user"></i>
                            {{ item.recordUserName }}
                          </span>
                        </el-tooltip>
                         
                       <span class="time">
                          <i class="el-icon-time"></i>
                          {{ item.watchTime }}
                        </span>
                    </div>
                  </div>
                </div>
              </el-scrollbar>
            </div>
          </div>
        </cardBox>

      </div>

      <div class="center-panel">
        <!-- VR/图像展示 -->
        <cardBox title="大坝实景监控" icon="&#xe62e;">
          <div class="card-body">
            <div class="visual-container">
              <div v-if="isVr === 1" class="vr-viewer">
                <div id="viewer" v-loading="loading.vr"></div>
              </div>
              <div v-else class="image-viewer">
                <img v-if="imgurlVR" :src="imgurlVR" @error="handleImageError" />
                <div v-else class="no-image">
                  <i class="el-icon-picture-outline"></i>
                  <p>暂无图片</p>
                </div>
              </div>
            </div>
            
            <div class="view-controls">
              <div class="view-options">
                <div v-for="(item, index) in imageArr" :key="index"
                      :class="['view-option', { active: item.name === currentName }]"
                      @click="setViewer(item)">
                  {{ item.name }}
                </div>
              </div>
            </div>
          </div>
        </cardBox>
        
        <div class="center-bot">
          <cardBox title="异常指标" icon="&#xe602;" isMore @more="ycDialogVisible = true">
            <template #right>
              <el-date-picker
                v-model="table2Time"
                type="date"
                size="small"
                :clearable="false"
                style="width:140px"
                @change="handleChangeTime"
                placeholder="请选择日期">
              </el-date-picker>
            </template>
            <div class="card-body warning-indicators">
              <noData showData v-if="tableData2.length === 0" style="height:320px"/>
              <div v-else class="warning-list">
                <div v-for="(item, index) in tableData2" :key="index" 
                     :class="['warning-item', getLevelClass(item.judgment)]">
                  <div class="warning-icon">
                    <i :class="['el-icon-success', getLevelClass(item.judgment)]" v-if="item.judgment == '正常'"></i>

                    <i :class="['el-icon-warning', getLevelClass(item.judgment)]" v-if="item.judgment != '正常'"></i>
                  </div>
                  <div class="warning-main">
                    <div class="warning-title">
                      <div>{{ item.index_Name }}</div>
                      <el-tag :type="getGradeTagType(item.judgment)" size="small">
                        {{ item.judgment }}
                      </el-tag>
                    </div>
                    <div class="warning-desc">{{ item.judemengtIllustrate }}</div>
                  </div>
                </div>
              </div>
            </div>
          </cardBox>
          
          <cardBox title="环境量监测" icon="&#xe62e;">
            <div class="card-body enviroment-wrapper" v-if="environment.length > 0">
              <environmenFactors :environment="environment"></environmenFactors>
            </div>
            <noData showData style="height:320px" v-else/>
          </cardBox>  
        </div>
      </div>

      <!-- 右侧信息面板 -->
      <div class="right-panel">
        <cardBox title="监测设备状态" icon="&#xe6fa;">
          <div class="card-body">
            <div class="status-display">
              <div class="status-chart">
                <div id="myChart" class="chart-container"></div>
              </div>
            </div>
          </div>
        </cardBox>
        
        <cardBox title="测值异常点" icon="&#xe67d;" isMore @more="ysDialogVisible = true">
          <div class="card-body abnormal-points">
            <noData showData v-if="tableData3.length === 0" style="height:200px"/>
            <div v-else class="abnormal-list">
              <div v-for="(item, index) in tableData3" :key="index" class="abnormal-item">
                <div class="point-header">
                  <el-tooltip effect="dark" content="测点名称" placement="top-start">
                    <div class="point-name">{{ item.pointName }}</div>
                  </el-tooltip>
                  <el-tooltip effect="dark" content="分量名称" placement="top-start">
                    <div class="comp-name">{{ item.compName }}</div>
                  </el-tooltip>
                </div>
                <div class="point-value">
                  <el-tooltip effect="dark" content="分量值" placement="top-start">
                    <span class="value">{{ item.compVal }}</span>
                  </el-tooltip>
                  <span class="unit">{{ item.unit }}</span>
                </div>
                <div class="point-limits">
                  <el-tooltip effect="dark" content="上限" placement="top-start">
                    <div class="limit">
                      <i class="el-icon-top upper"></i>
                      <span>{{ item.upperLimit || '-' }}</span>
                    </div>
                  </el-tooltip>
                  <el-tooltip effect="dark" content="下限" placement="top-start">
                    <div class="limit">
                      <i class="el-icon-bottom lower"></i>
                      <span>{{ item.lowerLimit || '-' }}</span>
                    </div>
                  </el-tooltip>
                </div>
                <div class="point-time">{{ item.watchtime }}</div>
              </div>
            </div>
          </div>
        </cardBox>
      </div>
    </div>


    <!-- 弹窗部分 -->
     <el-dialog title="巡视检查" v-dialogDrag :visible.sync="xsDialogVisible" width="90%">
        <el-table :data="tableData4" border stripe height="620">
          <el-table-column align="center" label="巡视日期" prop="watchTime" />
          <el-table-column align="center" label="巡查部位" prop="treeName" />
          <el-table-column align="center" label="巡视要求" prop="request" />
          <el-table-column align="center" label="巡查内容" prop="cont" />
          <el-table-column align="center" label="巡查情况" prop="remark" />
          <el-table-column align="center" label="照片/视频" prop="inspectionFiles" width="150">
            <template slot-scope="scope" v-if="scope.row.inspectionFiles.length > 0">
              <el-image
                style="width: 120px;"
                :src="scope.row.inspectionFiles[0].url"
                ></el-image>
            </template>
          </el-table-column>
          <el-table-column align="center" label="评判" prop="judgement">
            <template slot-scope="scope">
              <el-tag 
                :type="getJudgementTagType(scope.row.judgement)" 
                size="small"
                class="judgement-tag"
              >
                {{ getJudgementDisplayText(scope.row.judgement) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="巡查人员" prop="recordUserName" />
          <el-table-column align="center" label="审核人员" prop="checkUserName"/> 
          
          <el-table-column align="center" label="审核状态" prop="status">
            <template slot-scope="scope">
             <el-tag 
              :type="getStatusTagType(scope.row.status)" 
              size="small"
              class="status-tag"
            >
              {{ getStatusDisplayText(scope.row.status) }}
            </el-tag>
            </template>
          </el-table-column>
        </el-table>
    </el-dialog>

    <el-dialog title="大坝实时安全评价" v-dialogDrag :visible.sync="dbDialogVisible" width="90%">
      <div class="date-box" style="margin-bottom: 20px;">
        <el-input prefix-icon="el-icon-date" style="width:160px" v-model="timeSign" readonly 
                  @focus="showDateBox = true" placeholder="请选择要查询月份" size="small"/>
        <div class="shape" v-show="showDateBox" @click="showDateBox = false"></div>
        <calendar v-show="showDateBox" class="date-con" :eventData="eventData" 
                  @month-select="handleSelectMonth" />
      </div>
      <el-table :data="tableData1" height="580" row-key="index_id" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" border stripe>
        <el-table-column prop="indexName" label="部位" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="等级" align="center">
         <template slot-scope="scope">
            <el-tag :type="getGradeTagType(scope.row.grade)" size="small">
              {{ getGradeDisplayText(scope.row.grade) }}
            </el-tag>
          </template>
        </el-table-column>
       <el-table-column label="异常指标统计" align="center">
          <el-table-column prop="nomal" label="正常" align="center"></el-table-column>
          <el-table-column prop="Ⅲ" label="Ⅲ级" align="center"></el-table-column>
          <el-table-column prop="Ⅱ" label="Ⅱ级" align="center"></el-table-column>
          <el-table-column prop="Ⅰ" label="Ⅰ级" align="center"></el-table-column>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="过程线" :visible.sync="viewerLineChartDialog" width="70%" :before-close="viewerCancel">
      <chartLine :chartData="viewerLineChartData" ref="chartRef"></chartLine>
    </el-dialog>

    <el-dialog title="测值异常点" v-dialogDrag :visible.sync="ysDialogVisible" width="90%">
      <el-table :data="tableData3" border stripe height="620px">
  
        <el-table-column prop="pointName" label="测点名称" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column prop="compName" label="分量名称" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column prop="compVal" label="分量值" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column prop="unit" label="单位" align="center"></el-table-column>
        <el-table-column prop="watchtime" label="时间" align="center"></el-table-column>
        <el-table-column prop="upperLimit" label="上限" align="center">
          <template slot-scope="scope">
            <span class="greenText">{{ scope.row.upperLimit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lowerLimit" label="下限" align="center">
          <template slot-scope="scope">
            <span class="redText">{{ scope.row.upperLimit }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="监控异常指标" v-dialogDrag :visible.sync="ycDialogVisible" width="60%">
      <el-date-picker
        v-model="table2Time"
        type="date"
        :clearable="false"
        @change="handleChangeTime"
        style="margin-bottom: 20px;"
        placeholder="请选择日期">
      </el-date-picker>
      <el-table :data="tableData2" border stripe height="580">
        <el-table-column prop="index_Name" label="指标名称" align="center"></el-table-column>
        <el-table-column label="预警等级" align="center">
          <template slot-scope="scope">
            <el-tag :type="getGradeTagType(scope.row.judgment)" size="small">
              {{ scope.row.judgment }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="judemengtIllustrate" label="评价结果" align="center"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import bus from '@/utils/eventBus.js';
import { Viewer } from 'photo-sphere-viewer'
import { MarkersPlugin } from 'photo-sphere-viewer/dist/plugins/markers'
import 'photo-sphere-viewer/dist/photo-sphere-viewer.css'
import 'photo-sphere-viewer/dist/plugins/markers.css'
import noData from '@/components/base/noData.vue'
import cardBox from "../../components/base/cardBox.vue";
import environmenFactors from '@/components/page/index/environmentFactors.vue'
import chartLine from '@/components/base/chartLine.vue'
import {
  GetDamSecondConclusion,
  getOutlierDatas,
  GetInstrumentStatusNumber,
  getStationInspectionData,
  GetQueryById,
  GetvrinfoStation,
  GetHydrographs,
  GetDamAbnormalIndex,
  GetVnvironmentalInfo,
  getCalcRecordList
} from "@/api/https";
import calendar from '@/components/page/monitoring/calendar.vue'

// 标签类型映射
const GRADE_TAG_TYPES = {
  '正常': 'success',
  'Ⅰ': 'danger',
  'Ⅱ': 'warning',
  'Ⅲ': 'primary',
  '轻微异常': 'primary',
  '一般异常': 'warning',
  '严重异常': 'danger',
  '重度异常': 'danger'
};

const JUDGEMENT_TAG_TYPES = {
  1: 'success',
  2: 'primary',
  3: 'warning',
  4: 'danger'
};

const STATUS_TAG_TYPES = {
  0: 'info',
  1: 'success',
  2: 'danger'
};

const JUDGEMENT_DISPLAY_TEXTS = {
  1: '正常',
  2: '轻微异常',
  3: '一般异常',
  4: '重度异常',
  4: '严重异常'
};

const STATUS_DISPLAY_TEXTS = {
  0: '未审核',
  1: '审核通过',
  2: '审核不通过'
};

export default {
  name: 'station',
  components: { noData, cardBox, calendar,environmenFactors,chartLine },
  data() {
    return {
      stationId: sessionStorage.getItem("stationId"),
      tableData1: [],
      tableData2: [],
      tableData3: [],
      tableData4: [],
      timeInfo: {},
      isVr: 1,
      imageArr: [],
      imgurlVR: '',
      lineList: [],
      markers: [],
      currentName: '',
      myChart: null,
      chartNode: [],
      environment: [],
      loading: {
        table1: false,
        table2: false,
        table3: false,
        table4: false,
        chart: false,
        vr: false
      },
      viewer: null,
      markersPlugin: null,
      showDateBox: false,
      timeSign: '',
      eventData: [],
      table2Time: '',
      viewerInitializing: false,
      xsDialogVisible:false,
      dbDialogVisible:false,
      ysDialogVisible:false,
      viewerLineChartData:null,
      viewerLineChartDialog:false,
      ycDialogVisible:false
    }
  },
  created() {
    this.initBasin();
    this.dataInit();
    this.getVR();
  },
  activated() {
    this.initBasin();
    const newStationId = sessionStorage.getItem("stationId");
    if (newStationId == this.stationId) {
      if (this.imgurlVR && !this.viewer) {
        this.getVR();
      }
      if (this.chartNode.length > 0) {
        this.drawPie();
      }
    } else {
      this.stationId = newStationId;
      this.dataInit();
      this.onGetCalcRecordList()
      this.getVR();
    }
  },
  deactivated() {
    this.clearPage();
    this.$refs.chartRef.cleanupChart();
  },
  beforeDestroy() {
    this.clearPage();
  },
  methods: {
    initBasin() {
      bus.$emit('showBasin', true);
      bus.$off('station-changed', this.handleStationChanged);
      bus.$on('station-changed', this.handleStationChanged);
    },
    
    // 清理资源
    clearPage() {
      this.destroyViewer();
      this.clearChart(true);
      bus.$off('station-changed', this.handleStationChanged);
      window.removeEventListener('resize', this.handleChartResize);
    },
    
    // 销毁 VR 查看器
    async destroyViewer() {
      if (this.viewer) {
        try {
          if (this.markersPlugin) {
            this.markersPlugin.off('select-marker');
          }
          this.viewer.destroy();
          const container = document.querySelector('#viewer');
          if (container) {
            container.innerHTML = '';
          }
        } catch (e) {
          console.error('Viewer销毁失败:', e);
        } finally {
          this.viewer = null;
          this.markersPlugin = null;
        }
      }
    },
    
    // 事件处理
    handleStationChanged(newStationId, targetRoute) {
      if (!targetRoute || targetRoute === this.$route.name) {
        this.stationId = newStationId;
        this.dataInit();
        this.onGetCalcRecordList()
        this.getVR();
      }
    },

    onGetCalcRecordList() {
      getCalcRecordList({
        station_id: this.stationId,
        timeTp: 2
      }).then(res => {
        if (res.isSuccess) {
          this.eventData = res.data || []
        }
      })
    },

    handleSelectMonth(date) {
      this.timeSign = `${date.year}-${date.month}`
      this.showDateBox = false
      this.fetchDamConclusion()
    },

    handleChangeTime(date) {
      this.table2Time = date
      this.fetchDamAbnormalIndex()
    },
    
    // 数据初始化
    async dataInit() {
      try {
        this.setLoadingState(true);
        
        await Promise.allSettled([
          this.fetchDamConclusion(),
          this.fetchDamAbnormalIndex(),
          this.fetchOutlierDatas(),
          this.fetchInstrumentStatus(),
          this.fetchInspectionData(),
          this.fetchVnvironmentalInfo()
        ]);
      } catch (error) {
        this.$message.error('数据加载失败，请稍后重试');
      } finally {
        this.setLoadingState(false);
      }
    },

    setLoadingState(isLoading) {
      Object.keys(this.loading).forEach(key => {
        if (key !== 'vr') {
          this.loading[key] = isLoading;
        }
      });
    },
    
    // API 调用方法
    async fetchDamConclusion() {
      try {
        const res = await GetDamSecondConclusion({
          stationID: this.stationId,
          time: this.timeSign
        });
        if (res.isSuccess) {
          this.tableData1 = res.data.indexsInfo || [];
          this.timeInfo = res.data.stationInfo || {};
        } 
      } catch (error) {
        console.error('获取大坝安全评价数据失败:', error);
      }
    },

    async fetchDamAbnormalIndex() {
      try {
        const res = await GetDamAbnormalIndex({
          stationID: this.stationId,
          dt: this.table2Time
        });
        if (res.isSuccess) {
          this.tableData2 = res.data || [];
          this.table2Time = res.data.length > 0 ? res.data[0].picktime : new Date()
        } 
      } catch (error) {
        console.error('获取异常指标数据失败:', error);
      }
    },
    
    async fetchOutlierDatas() {
      try {
        const res = await getOutlierDatas({
          STATION_ID: this.stationId
        });
        if (res.isSuccess) {
          this.tableData3 = res.data || [];
        } 
      } catch (error) {
        console.error('获取测值异常点数据失败:', error);
      }
    },
    
    async fetchInstrumentStatus() {
      try {
        const res = await GetInstrumentStatusNumber(this.stationId);
        if (res.isSuccess && res.data?.node?.length > 0) {
          this.chartNode = res.data.node;
          this.$nextTick(() => {
            this.drawPie();
          });
        } else {
          this.clearChart();
        }
      } catch (error) {
        console.error('获取监测设备状态数据失败:', error);
      }
    },
    
    async fetchInspectionData() {
      try {
        const res = await getStationInspectionData({
          StationID: this.stationId
        });
        if (res.isSuccess) {
          this.tableData4 = res.data || [];
        } 
      } catch (error) {
        console.error('获取巡视检查数据失败:', error);
      }
    },

    async fetchVnvironmentalInfo() {
      try {
        const res = await GetVnvironmentalInfo({
          staionID: this.stationId,
          time: '2025/9/1'
        });
        this.environment = res.isSuccess ? res.data || [] : [];
      } catch (error) {
        console.error('获取环境监测数据失败:', error);
        this.environment = [];
      }
    },
    
    // VR 相关方法
    async getVR() {
      this.loading.vr = true;
      try {
        await this.destroyViewer();
        
        const res = await GetQueryById(this.stationId);
        if (res.isSuccess && res.data?.imgs?.length > 0) {
          const firstImage = res.data.imgs[0];
          this.isVr = firstImage.is_vr;
          this.imageArr = res.data.imgs;
          this.imgurlVR = firstImage.img_path;
          this.currentName = firstImage.name;
          await this.getVrInfo();
        } else {
          this.isVr = 0;
          this.imageArr = [];
          this.imgurlVR = '';
        }
      } catch (error) {
        console.error('获取VR信息失败:', error);
        this.$message.error('VR信息加载失败');
      } finally {
        this.loading.vr = false;
      }
    },
    
    async getVrInfo() {
      try {
        const res = await GetvrinfoStation(this.stationId);
        if (res.isSuccess) {
          this.markers = (res.data.vrs || [])
            .filter(marker => !isNaN(parseFloat(marker.longitude)) && !isNaN(parseFloat(marker.latitude)))
            .map(marker => ({
              ...marker,
              longitude: parseFloat(marker.longitude),
              latitude: parseFloat(marker.latitude)
            }));
          
          await this.initViewer(res.data);
        }
      } catch (error) {
        console.error('获取VR详情失败:', error);
      }
    },
    
    async initViewer(vrData) {
      if (this.isVr !== 1) return;
      const container = document.querySelector('#viewer');
      if (!container || this.viewerInitializing) return;
      
      this.viewerInitializing = true;
      
      try {
        await this.destroyViewer();
        await this.$nextTick();
        
        const initialX = !isNaN(parseFloat(vrData.x)) ? parseFloat(vrData.x) : 0;
        const initialY = !isNaN(parseFloat(vrData.y)) ? parseFloat(vrData.y) : 0;
        
        this.viewer = new Viewer({
          container: container,
          panorama: this.imgurlVR,
          moveSpeed: 1,
          autorotateSpeed: 0.12943951023931953,
          size: {
            width: '100%',
            height: 'calc(100vh - 400px)',
          },
          plugins: [
            [MarkersPlugin, {
              markers: this.markers || [],
            }]
          ]
        });
        
        this.viewer.once('ready', () => {
          this.viewer.rotate({
            x: initialX,
            y: initialY
          });
          this.markersPlugin = this.viewer.getPlugin(MarkersPlugin);
          this.markersPlugin.on('select-marker', (e, marker) => {
            this.getGraphs(marker);
          });
          this.viewerInitializing = false;
        });
      } catch (error) {
        console.error('初始化VR查看器失败:', error);
        this.viewerInitializing = false;
      }
    },
    
    async getGraphs(marker) {
      try {
        const res = await GetHydrographs(this.stationId, marker.config.tooltip.content);
        if (res.isSuccess && res.data?.length > 0) {
          this.viewerLineChartData = res.data[0].data;
          this.viewerLineChartDialog = true
        }else{
          this.viewerLineChartData = null
          this.$message.error(res.errorMessage)
        }
      } catch (error) {
        this.error('获取图表数据失败:', error);
      }
    },
    viewerCancel(){
      this.viewerLineChartData = null;
      this.viewerLineChartDialog = false
      this.$refs.chartRef.clearChart();
    },
    async setViewer(data) {
      this.loading.vr = true;
      try {
        this.isVr = data.is_vr;
        this.currentName = data.name;
        
        if (data.is_vr === 1) {
          if (!this.viewer) {
            await this.initViewer({ x: 0, y: 0, vrs: [] });
          }
          if (this.viewer) {
            await this.viewer.setPanorama(data.img_path);
            if (this.markersPlugin) {
              const action = data.name !== '坝顶' ? 'hideMarker' : 'showMarker';
              this.markers.filter(m => m.id).forEach(marker => {
                this.markersPlugin[action](marker.id);
              });
            }
          }
        } else {
          this.imgurlVR = data.img_path;
          await this.destroyViewer();
        }
      } catch (error) {
        console.error('切换视图失败:', error);
      } finally {
        this.loading.vr = false;
      }
    },
    
    // 图表方法
    drawPie() {
      if (!this.chartNode?.length) {
        this.clearChart();
        return;
      }
      
      try {
        const chartDom = document.getElementById('myChart');
        if (!chartDom) return;
        
        if (this.myChart) {
          this.myChart.dispose();
        }
        
        this.myChart = this.$echarts.init(chartDom, null, { locale: "ZH" });
        
        const newData = this.chartNode.map(item => ({
          value: item.value,
          name: `${item.name}:(${item.value})`
        }));
        
        const option = {
          legend: {
            orient: 'vertical',
            right: 10,
            top: 15,
            bottom: 10,
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          series: [{
            name: '设备状态',
            minAngle: 6,
            type: 'pie',
            radius: ['40%', '80%'],
            center: ['30%', '50%'],
            avoidLabelOverlap: false,
            padAngle: 5,
            itemStyle: { borderRadius: 10 },
            label: { show: false, position: 'center' },
            emphasis: {
              label: { show: true, fontSize: 14, fontWeight: 'bold' }
            },
            labelLine: { show: false },
            data: newData
          }]
        };
        
        this.myChart.setOption(option, true);
        window.addEventListener('resize', this.handleChartResize);
      } catch (error) {
        console.error('绘制饼图失败:', error);
      }
    },
    
    handleChartResize() {
      this.myChart?.resize();
    },
    
    clearChart(dispose = false) {
      if (this.myChart) {
        this.myChart.clear();
        if (dispose) {
          this.myChart.dispose();
          this.myChart = null;
        }
      }
    },

    handleImageError() {
      this.imgurlVR = '';
    },

    // 工具方法
    getGradeTagType(grade) {
      return GRADE_TAG_TYPES[grade] || 'info';
    },

    getGradeDisplayText(grade) {
      return grade === '正常' ? '正常' : `${grade}`;
    },

    getJudgementTagType(judgement) {
      return JUDGEMENT_TAG_TYPES[judgement] || 'info';
    },

    getJudgementDisplayText(judgement) {
      return JUDGEMENT_DISPLAY_TEXTS[judgement] || '';
    },

    getStatusTagType(status) {
      return STATUS_TAG_TYPES[status] || 'info';
    },

    getStatusDisplayText(status) {
      return STATUS_DISPLAY_TEXTS[status] || '';
    },

    getLevelClass(judgment) {
      const reversedMap = {};
        for (const key in JUDGEMENT_DISPLAY_TEXTS) {
          if (JUDGEMENT_DISPLAY_TEXTS.hasOwnProperty(key)) {
            reversedMap[JUDGEMENT_DISPLAY_TEXTS[key]] = key;
          }
        }
        const levelKey = reversedMap[judgment];
        
        return levelKey ? `level-${levelKey}` : undefined;
        }
      }
}
</script>

<style scoped lang="scss"> 
.dashboard-content {
  display: grid;
  grid-template-columns:  440px 1fr 380px;
  gap: 10px;
  padding-bottom: 30px;
  box-sizing: border-box;
  margin-top:-10px;
  .boxWrapper{
    margin-top:10px;
  }
}

.card-body {
    padding: 20px;
}

// 安全评价样式
.table-wrapper{
    padding:10px;
}

// 环境监测样式
.enviroment-wrapper{
    height: 360px;
    overflow: auto;
}
.environment-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
    
    
    .env-item {
      display: flex;
      align-items: center;
      padding: 15px;
      background: #f9fafc;
      border-radius: 8px;
      
      .env-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40px;
        height: 40px;
        border-radius: 8px;
        margin-right: 15px;
        font-size: 20px;
        
        &.temperature {
          background: #fff2e8;
          color: #fa541c;
        }
        
        &.rainfall {
          background: #e3f1ea;
          color: #1890ff;
        }
        
        &.water {
          background: #f0f9ff;
          color: #1890ff;
           i{
            font-size: 20px;
          }
        }
        
        &.flow {
          background: #fafff1;
          color: #7ace4f;
          i{
            font-size: 20px;
          }
        }
      }
      
      .env-info {
        .value {
          font-size: 18px;
          font-weight: 700;
          color: #303133;
          width:106px;
          text-overflow: ellipsis;
          overflow: hidden;
          height: 24px;
        }
        
        .label {
          font-size: 13px;
          color: #909399;
        }
      }
    }
  }

// 中央视觉展示区

.visual-container {
    height: 414px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    
    .vr-viewer, .image-viewer {
      height: 100%;
      width: 100%;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .no-image {
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #909399;
        background: #fafafa;
        
        .el-icon {
          font-size: 48px;
          margin-bottom: 16px;
        }
      }
    }
  }
  
.view-controls {
margin-top: 16px;

.view-options {
    display: flex;
    gap: 8px;
    
    .view-option {
    padding: 8px 16px;
    border-radius: 20px;
    background: #f5f5f5;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
        background: #e6f7ff;
        color: #1890ff;
    }
    
    &.active {
        background: #1890ff;
        color: white;
        box-shadow: 0 2px 8px rgba(24, 144, 255, 0.4);
    }
    }
}
}

// 警告指示器样式
.warning-indicators {
    height: 360px;
  .warning-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
    height: 310px;
    overflow-y:auto ;
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE/Edge */
  }
  
  .warning-item {
    display: flex;
    align-items: center;
    padding: 16px;
    border-radius: 12px;
    background: #f8f9fa;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateX(4px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    &.level-1 {
      border-left: 4px solid #52c41a;
    }
    
    &.level-2 {
      border-left: 4px solid #1890ff;
    }
    
    &.level-3 {
      border-left: 4px solid #faad14;
    }
    
    &.level-4 {
      border-left: 4px solid #f5222d;
    }
    
    .warning-icon {
      margin-right: 16px;
      font-size: 20px;
      
      i.level-1 {
        color: #52c41a;
      }
      
      i.level-2 {
       color: #1890ff;
      }
      
      i.level-3 {
        color: #faad14;
      }
      
      .level-4 {
        color: #f5222d;
      }
    }
    
    .warning-main {
      flex: 1;
      
      .warning-title {
        font-weight: 600;
        margin-bottom: 4px;
        color: #303133;
        font-size: 14px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
      }
      
      .warning-desc {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

// 设备状态样式

  .status-display {
    display: flex;
    align-items: center;
    
    .status-chart {
      width: 360px;
      height: 160px;
      
      .chart-container {
        width: 100%;
        height: 100%;
      }
    }
    
    .status-legend {
      flex: 1;
      padding-left: 20px;
      
      .legend-item {
        display: flex;
        align-items: center;
        margin-bottom: 16px;
        
        .color-dot {
          width: 12px;
          height: 12px;
          border-radius: 50%;
          margin-right: 12px;
          
          &.status-0 { background: #52c41a; }
          &.status-1 { background: #faad14; }
          &.status-2 { background: #f5222d; }
        }
        
        .legend-label {
          flex: 1;
          font-size: 14px;
          color: #606266;
        }
        
        .legend-value {
          font-weight: 700;
          color: #1a73e8;
          font-size: 16px;
        }
      }
    }
  }

// 异常点样式
.abnormal-points {
    height: 665px;
  .abnormal-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
    height: 630px;
    overflow-y: auto;
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE/Edge */
  }
  
  .abnormal-item {
    padding: 20px;
    border-radius: 8px;
    background: #f8f9fa;
    border: 1px solid #eaecef;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      background: #fff;
    }
    
    .point-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 12px;
      
      .point-name {
        font-weight: 600;
        color: #303133;
        font-size: 14px;
      }
      
      .comp-name {
        color: #303133;
        font-size: 12px;
        font-weight: 600;
        font-size: 14px;
      }
    }
    
    .point-value {
      margin-bottom: 12px;
      
      .value {
        font-size: 28px;
        font-weight: 700;
        color: #1890ff;
      }
      
      .unit {
        font-size: 14px;
        color: #909399;
        margin-left: 4px;
      }
    }
    
    .point-limits {
      display: flex;
      gap: 20px;
      margin-bottom: 12px;
      
      .limit {
        display: flex;
        align-items: center;
        font-size: 14px;
        
        .upper { color: #52c41a; }
        .lower { color: #f5222d; }
        
        i {
          margin-right: 6px;
          font-weight: bold;
        }
      }
    }
    
    .point-time {
      font-size: 12px;
      color: #909399;
      text-align: right;
    }
  }
}

// 巡视检查样式
.inspection {
  padding: 12px 12px 24px 12px;

  
  .inspection-list {
   overflow-y:auto ;
    height: 480px;
    scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */
  }
  
  .inspection-container {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  
  .inspection-item {
    background: #fff;
    border-radius: 6px;
    border: 1px solid #e8e8e8;
    padding: 12px;
    transition: all 0.2s ease;
    
    &:hover {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      border-color: #d0d5dd;
    }
  }
  
  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 8px;
    gap: 8px;
    
    .header-main {
      flex: 1;
      min-width: 0;
      
      .location {
        display: block;
        font-size: 14px;
        font-weight: 600;
        color: #1a1a1a;
        margin-bottom: 2px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        
        i {
          margin-right: 4px;
          color: #409EFF;
          font-size: 14px;
        }
      }
      
    }
    
    .header-status {
      display: flex;
      flex-direction: row;
      gap: 4px;
      align-items: center;
      flex-shrink: 0;
      .ico{
        font-size: 18px;
        margin-left: 6px;
        vertical-align: middle;
        padding-top:-20px;
        font-weight: bold;
      }
    }
  }
  
  .item-content {
    margin: 8px 0;
    
    .content-row {
      display: flex;
      margin-bottom: 6px;
      font-size: 14px;
      line-height: 1.4;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .label {
        flex-shrink: 0;
        color: #666;
        font-weight: 500;
        width: 80px;
      }
      
      .value {
        flex: 1;
        color: #333;
        word-break: break-word;
        
        &.content-text {
          background: #f9f9f9;
          padding: 4px 6px;
          border-radius: 3px;
          border-left: 2px solid #e8e8e8;
        }
      }
    }
  }
  
  .item-footer {
    border-top: 1px dashed #e8e8e8;
    padding-top: 6px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    .inspector {
      font-size: 12px;
      color: #888;
      
      i {
        margin-right: 3px;
        font-size: 12px;
      }
    }

    .time {
        font-size: 12px;
        color: #666;
        padding-top: 2px;
        i {
          margin-right: 2px;
          font-size: 12px;
        }
      }
  }
}

.date-box{
  position: relative;
  .shape{
    position: fixed;
    top:0;
    left:0;
    right:0;
    bottom: 0;
    z-index: 2000;
  }
  .date-con{
    position:absolute;
    top:40px;
    left:0;
    transform-origin: center top;
    z-index: 2001;
  }
}
.center-bot{
    flex:1;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
}
</style>